import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.*;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

/**
 * pdf工具类
 *
 * @author duanjw
 */
@UtilityClass
public class PdfUtils {
    /**
     * pdf加密
     *
     * @param inputFile
     * @param outputFile
     * @param userPassWord
     * @param ownerPassWord
     */
    @SneakyThrows
    public void encryption(String inputFile, String outputFile,
                           String userPassWord, String ownerPassWord) {
        PdfReader reader = new PdfReader(inputFile);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(
                outputFile));
        // 设置密码
        stamper.setEncryption(userPassWord.getBytes(), ownerPassWord
                .getBytes(), PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);
        stamper.close();
    }

    /**
     * pdf文字水印
     *
     * @param inputFile
     * @param outputFile
     * @param waterMarkName
     */
    @SneakyThrows
    public void mark(String inputFile, String outputFile, String waterMarkName) {
        PdfReader reader = new PdfReader(inputFile);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(
                outputFile));
        BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
                BaseFont.NOT_EMBEDDED);
        int total = reader.getNumberOfPages() + 1;
//        Image image = Image.getInstance("/Users/duanjw/Downloads/云平台1.0.png");
//        image.setAbsolutePosition(200, 400);
        PdfContentByte under;
        int j = waterMarkName.length();
        char c = 0;
        int rise = 0;
        for (int i = 1; i < total; i++) {
            rise = 500;
            under = stamper.getUnderContent(i);
            // 添加图片
            // under.addImage(image);
            under.beginText();
            under.setColorFill(BaseColor.LIGHT_GRAY);
            under.setFontAndSize(base, 50);
            // 设置水印文字字体倾斜 开始
            if (j >= 15) {
                under.setTextMatrix(200, 120);
                for (int k = 0; k < j; k++) {
                    under.setTextRise(rise);
                    c = waterMarkName.charAt(k);
                    under.showText(c + "");
                    rise -= 0;
                }
            } else {
                under.setTextMatrix(180, 100);
                for (int k = 0; k < j; k++) {
                    under.setTextRise(rise);
                    c = waterMarkName.charAt(k);
                    under.showText(c + "");
                    rise -= 0;
                }
            }
            // 字体设置结束
            under.endText();
            // 画一个圆
            // under.ellipse(250, 450, 350, 550);
            // under.setLineWidth(1f);
            // under.stroke();

        }
        stamper.close();
    }
    @SneakyThrows
    void wordToPdf(){
//        FileInputStream input = new FileInputStream("/Users/duanjw/Downloads/1.docx");
//        OutputStream out = new FileOutputStream("/Users/duanjw/Downloads/1.pdf");
//
//        XWPFDocument doc = new XWPFDocument(input);
//
//        PdfOptions options = PdfOptions.create();
//
//        PdfConverter.getInstance().convert(doc, out, options);
    }
//
//    /**
//     * docx文档转换为PDF
//     * @param body 文档
//     * @param response 响应给前端
//     * @return pdf 输出流
//     * @throws Exception 可能为Docx4JException, FileNotFoundException, IOException等
//     */
//    public static void convertDocxToPdf(byte[] body , HttpServletResponse response) throws Exception {
//        response.setContentType("application/pdf");
//        File docxFile = FileUtil.byteToFile(body, UUID.randomUUID().toString() + ".docx");
//        try {
//            WordprocessingMLPackage mlPackage = WordprocessingMLPackage.load(docxFile);
//            setFontMapper(mlPackage);
//            Docx4J.toPDF(mlPackage, response.getOutputStream());
//        }catch (Exception e){
//            e.printStackTrace();
//            log.error("docx文档转换为PDF失败");
//        }
//        FileUtil.deleteTempFile(docxFile);
//    }
//


//    /**
//     * docx文档转换为PDF
//     *
//     * @param pdfPath PDF文档存储路径
//     * @throws Exception 可能为Docx4JException, FileNotFoundException, IOException等
//     */
//    public static void convertDocxToPdf(String docxPath, String pdfPath) throws Exception {
//
//        FileOutputStream fileOutputStream = null;
//        try {
//            File file = new File(docxPath);
//            fileOutputStream = new FileOutputStream(new File(pdfPath));
//            WordprocessingMLPackage mlPackage = WordprocessingMLPackage.load(file);
//            setFontMapper(mlPackage);
//            Docx4J.toPDF(mlPackage, new FileOutputStream(new File(pdfPath)));
//        }catch (Exception e){
//            e.printStackTrace();
////            log.error("docx文档转换为PDF失败");
//        }finally {
//            IOUtils.closeQuietly(fileOutputStream);
//        }
//    }
//
//    private static void setFontMapper(WordprocessingMLPackage mlPackage) throws Exception {
//        Mapper fontMapper = new IdentityPlusMapper();
//        fontMapper.put("隶书", PhysicalFonts.get("LiSu"));
//        fontMapper.put("宋体", PhysicalFonts.get("SimSun"));
//        fontMapper.put("微软雅黑", PhysicalFonts.get("Microsoft Yahei"));
//        fontMapper.put("黑体", PhysicalFonts.get("SimHei"));
//        fontMapper.put("楷体", PhysicalFonts.get("KaiTi"));
//        fontMapper.put("新宋体", PhysicalFonts.get("NSimSun"));
//        fontMapper.put("华文行楷", PhysicalFonts.get("STXingkai"));
//        fontMapper.put("华文仿宋", PhysicalFonts.get("STFangsong"));
//        fontMapper.put("宋体扩展", PhysicalFonts.get("simsun-extB"));
//        fontMapper.put("仿宋", PhysicalFonts.get("FangSong"));
//        fontMapper.put("仿宋_GB2312", PhysicalFonts.get("FangSong_GB2312"));
//        fontMapper.put("幼圆", PhysicalFonts.get("YouYuan"));
//        fontMapper.put("华文宋体", PhysicalFonts.get("STSong"));
//        fontMapper.put("华文中宋", PhysicalFonts.get("STZhongsong"));
//
//        mlPackage.setFontMapper(fontMapper);
//    }
    @SneakyThrows
    public static void main(String[] args) {
//        encryption("/Users/duanjw/Downloads/Java-huashanxinban的副本.pdf", "/Users/duanjw/Downloads/Java1-huashanxinban.pdf", "123", "123");
//        mark("/Users/duanjw/Downloads/Java-huashanxinban的副本.pdf", "/Users/duanjw/Downloads/Java1-huashanxinban.pdf", "我是水印");
//    wordToPdf();
//        convertDocxToPdf("/Users/duanjw/Downloads/1.docx","/Users/duanjw/Downloads/1.pdf");
    }
}
